<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.category_name"
        placeholder="分类名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      style="width: 100%;"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类名称" min-width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.category_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sort_order }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" @click="handleAddChild(row)">
            添加子分类
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="分类名称" prop="category_name">
          <el-input v-model="temp.category_name" />
        </el-form-item>
        <el-form-item label="父级分类" prop="parent_id" v-if="dialogStatus !== 'addChild'">
          <el-select v-model="temp.parent_id" placeholder="请选择父级分类" style="width: 100%">
            <el-option label="无父级分类" :value="0" />
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.category_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="temp.sort_order" :min="0" :max="1000" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():(dialogStatus==='update'?updateData():createChildData())">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { http } from '@/api'

export default {
  name: 'ItemCategory',
  data() {
    return {
      list: null,
      categoryOptions: [],
      listLoading: true,
      listQuery: {
        category_name: undefined
      },
      temp: {
        id: undefined,
        category_name: '',
        parent_id: 0,
        sort_order: 0,
        remark: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑分类',
        create: '新增分类',
        addChild: '添加子分类'
      },
      rules: {
        category_name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
        sort_order: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      http.itemCategory.list(this.listQuery).then(response => {
        // 处理数据为树形结构
        this.list = this.handleTreeData(response.data)
        this.categoryOptions = response.data
        this.listLoading = false
      })
    },
    // 将平铺数据转换为树形结构
    handleTreeData(data) {
      const result = []
      const map = {}

      // 先将数据转为map便于查找
      data.forEach(item => {
        map[item.id] = { ...item, children: [] }
      })

      // 构建树形结构
      data.forEach(item => {
        const parent = map[item.parent_id]
        if (parent) {
          parent.children.push(map[item.id])
        } else {
          result.push(map[item.id])
        }
      })

      return result
    },
    handleFilter() {
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        category_name: '',
        parent_id: 0,
        sort_order: 0,
        remark: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          http.itemCategory.create(null, this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleAddChild(row) {
      this.resetTemp()
      this.temp.parent_id = row.id
      this.dialogStatus = 'addChild'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createChildData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          http.itemCategory.create(null, this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建子分类成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          http.itemCategory.update(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      // 如果有子分类，不允许删除
      if (row.children && row.children.length > 0) {
        this.$message.error('该分类下有子分类，不能删除')
        return
      }

      this.$confirm('确认删除该分类?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.itemCategory.delete(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-bottom: 10px;
  margin-right: 10px;
}
</style>
